package com.work.leecode.string.middle;

import java.util.ArrayList;
import java.util.List;

/**
 * Z字形变换
 */
public class Lc6 {
    public String convert(String s, int numRows) {
        //前置判断
        if (numRows < 2) {
            return s;
        }

        List<StringBuilder> rows = new ArrayList<>();

        //初始化rows
        for (int i = 0; i < numRows; i++) {
            rows.add(new StringBuilder());
        }

        //辅助变量
        int flag = -1;
        int i = 0;

        for (char c : s.toCharArray()) {
            //先添加再判断
            rows.get(i).append(c);
            if (i == 0 || i == numRows - 1) {//在最上面或者最下面
                flag = -flag;
            }
            i += flag;
        }

        //返回的结果
        StringBuilder res = new StringBuilder();
        for (StringBuilder row : rows) {
            res.append(row);
        }
        return res.toString();
    }

    //复习2024.05.05
    public String convert2(String s, int numRows) {
        if (numRows < 2) {
            return s;
        }

        List<StringBuilder> rows = new ArrayList<>();

        //初始化rows
        for (int i = 0; i < numRows; i++) {
            rows.add(new StringBuilder());
        }

        //辅助变量
        int flag = -1;
        int index = 0;//用于控制取得是哪个StringBuilder

        //循环遍历字符串，填充rows
        for (int i = 0; i < s.length(); i++) {
            rows.get(index).append(s.charAt(i));
            if (index == 0 || index == numRows - 1) {
                flag = -flag;
            }
            index += flag;
        }

        StringBuilder res = new StringBuilder();
        for (StringBuilder row : rows) {
            res.append(row);
        }
        return res.toString();
    }
}
